package com.own.component.util.sensitive;

import com.own.component.util.sensitive.model.UpdateModel;

import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;

/**
 * SensitiveWordUtil
 *
 * @author chenxueli
 * @date 2023-07-03 16:16:00
 */
public class SensitiveWordUtil {

    public static final SensitiveWordFilter INSTANCE = new SensitiveWordFilter();

    /**
     * 敏感词操作类型
     */
    private static final Map<String, BiConsumer<SensitiveWordFilter, UpdateModel>> SENSITIVE_WORD_MAP = new HashMap<>() {{
        put("add", (instance, model) -> {
            if (model.getNewContent() == null || model.getNewContent().isEmpty()) {
                throw new RuntimeException("敏感词信息为空");
            }
            // 新增
            instance.add(model.getNewContent());
        });
        put("update", (instance, model) -> {
            if (model.getNewContent() == null || model.getNewContent().isEmpty() || model.getOldContent() == null || model.getOldContent().isEmpty()) {
                throw new RuntimeException("敏感词信息为空");
            }
            if (model.getOldContent().equals(model.getNewContent())) {
                return;
            }
            // 修改
            instance.remove(model.getOldContent());
            instance.add(model.getNewContent());
        });
        put("delete", (instance, model) -> {
            if (model.getOldContent() == null || model.getOldContent().isEmpty()) {
                throw new RuntimeException("敏感词信息为空");
            }
            // 删除
            instance.remove(model.getOldContent());
        });
    }};

    /**
     * 修改信息
     *
     * @param model 修改信息
     */
    public static void update(UpdateModel model) {
        update(INSTANCE, model);
    }

    /**
     * 修改信息
     *
     * @param instance 敏感词过滤器
     * @param model    修改信息
     */
    public static void update(SensitiveWordFilter instance, UpdateModel model) {
        if (!SENSITIVE_WORD_MAP.containsKey(model.getOperation())) {
            throw new RuntimeException("敏感词操作类型不正确");
        }
        var handler = SENSITIVE_WORD_MAP.get(model.getOperation());
        handler.accept(instance, model);
    }

}
